/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.cloud.business.usercenter.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.lvyh.lightframe.cloud.business.usercenter.bean.UcSysRoleBean;
import com.lvyh.lightframe.cloud.business.usercenter.service.SysMenuService;
import com.lvyh.lightframe.cloud.business.usercenter.service.SysPermissionService;
import com.lvyh.lightframe.cloud.business.usercenter.service.UserCenterMainDataService;
import com.lvyh.lightframe.cloud.common.constant.SystemConstants;
import com.lvyh.lightframe.cloud.common.model.SysMenu;
import com.lvyh.lightframe.cloud.common.model.SysPermission;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SysPermissionServiceImpl implements SysPermissionService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private UserCenterMainDataService userCenterMainDataService;

    @Override
    public List<SysPermission> listPermRoles() throws Exception {
        List<SysPermission> result = new ArrayList<>();
        List<SysMenu> sysMenuList = sysMenuService.findAll();
        if (!CollectionUtils.isEmpty(sysMenuList)) {
            for (SysMenu sysMenu : sysMenuList) {
                Integer roleId = sysMenuService.getRoleInfoByMenuId(sysMenu.getId());
                List<String> sysRoleCodes = getSysRoleCodes(roleId);
                SysPermission sysPermission = new SysPermission();
                sysPermission.setUrlPerm(sysMenu.getPathMethod() + ":" + sysMenu.getUrl());
                sysPermission.setRoles(sysRoleCodes);
                result.add(sysPermission);
            }
        }

        return result;
    }

    private List<String> getSysRoleCodes(Integer roleId) throws Exception {
        List<String> result = new ArrayList<>();
        UcSysRoleBean condition = new UcSysRoleBean();
        condition.setId(roleId);
        List<UcSysRoleBean> sysRoleList = userCenterMainDataService.selectUcSysRole(condition);
        if (!org.springframework.util.CollectionUtils.isEmpty(sysRoleList)) {
            for (UcSysRoleBean sysRoleBean : sysRoleList) {
                result.add(sysRoleBean.getCode());
            }
        }
        return result;
    }

    @Override
    public boolean refreshPermRolesRules() throws Exception {
        redisTemplate.delete(Arrays.asList(SystemConstants.URL_PERM_ROLES_KEY, SystemConstants.BTN_PERM_ROLES_KEY));
        List<SysPermission> permissions = this.listPermRoles();
        if (CollectionUtil.isNotEmpty(permissions)) {
            // 初始化URL【权限->角色(集合)】规则
            List<SysPermission> urlPermList = permissions.stream()
                    .filter(item -> StrUtil.isNotBlank(item.getUrlPerm()))
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(urlPermList)) {
                Map<String, List<String>> urlPermRoles = new HashMap<>();
                urlPermList.stream().forEach(item -> {
                    String perm = item.getUrlPerm();
                    List<String> roles = item.getRoles();
                    urlPermRoles.put(perm, roles);
                });
                redisTemplate.opsForHash().putAll(SystemConstants.URL_PERM_ROLES_KEY, urlPermRoles);
                //redisTemplate.convertAndSend("cleanRoleLocalCache","true");
            }
            // 初始化URL【按钮->角色(集合)】规则
            List<SysPermission> btnPermList = permissions.stream()
                    .filter(item -> StrUtil.isNotBlank(item.getBtnPerm()))
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(btnPermList)) {
                Map<String, List<String>> btnPermRoles = CollectionUtil.newHashMap();
                btnPermList.stream().forEach(item -> {
                    String perm = item.getBtnPerm();
                    List<String> roles = item.getRoles();
                    btnPermRoles.put(perm, roles);
                });
                redisTemplate.opsForHash().putAll(SystemConstants.BTN_PERM_ROLES_KEY, btnPermRoles);
            }
        }
        return true;
    }

}
